﻿using System;
using System.Collections.Generic;
using Gumini.JulaDB.DataTypes;
using Gumini.JulaDB.Expressions;
using Gumini.JulaDB.Interfaces;

namespace Gumini.JulaDB.Engine
{
    /// <summary>
    /// Represents a column that is created for the time of query evaluation.
    /// </summary>
    internal class TemporaryColumn : IColumn
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TemporaryColumn"/> class.
        /// </summary>
        /// <param name="type">The type of the data to be stored in the column.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="tableNames">The table names of the source table (might contain both actual name and table alias).</param>
        /// <param name="expression">The expression used to create values in this column.</param>
        public TemporaryColumn(DataType type, string columnName, List<string> tableNames, Expression expression = null)
        {
            this.Type = type;
            this.ColumnName = columnName;

            var allNames = new List<string> { columnName };
            foreach (var tableName in tableNames)
                allNames.Add(String.Format("{0}.{1}", tableName, columnName));
            this.AllNames = allNames;
        }

        /// <summary>
        /// Type of the values stored in the column.
        /// Might be null when type cannot be determined (e.g. when column was created from a null constant).
        /// </summary>
        public DataType Type { get; private set; }

        /// <summary>
        /// The name of the column.
        /// </summary>
        public string ColumnName { get; private set; }

        /// <summary>
        /// The expression used to create values in this column. Might be null.
        /// </summary>
        public Expression ColumnExpression { get; private set; }

        /// <summary>
        /// All of the names that might refer to this particular column, e.g. 'name', 'person.name', 'p.name'.
        /// </summary>
        public IEnumerable<string> AllNames { get; private set; }

        public override string ToString()
        {
            return String.Format("{0} (type: {1}, names: [{2}])", ColumnName, Type, string.Join(",", AllNames));
        }
    }
}
